<template>
  <FormTableLayout>
    <template #form>汉字结构</template>
    <template #tools>
      <el-button :icon="Plus" type="primary" size="small" plain @click="handleClickBtnAdd">新建</el-button>
    </template>
    <template #default>
      <el-table :data="tableData" row-key="id" style="width: 100%" border scrollbar-always-on header-cell-class-name="table-header-row" empty-text="没有数据">
        <el-table-column prop="name" label="结构名称" width="200" />
        <el-table-column prop="description" label="解释" width="300" />
        <el-table-column prop="create_time" label="创建时间" width="180" />
        <el-table-column prop="update_time" label="更新时间" width="180" />
        <el-table-column label="操作" width="200" header-align="right" align="right">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" @click="handleClickBtnEdit(scope.row)" size="small" link>编辑</el-button>
            <el-button type="danger" :icon="Delete" @click="handleClickBtnDelete(scope.row.id)" size="small" link>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #other>
      <DrawersEdit ref="refDrawersEdit" @submited="handleDrawersEditSubmited" />
    </template>
  </FormTableLayout>
</template>

<script setup lang="ts">
import FormTableLayout from '@/layout/FormTableLayout.vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import DrawersEdit from './drawers/Edit.vue'
import Dal from '@/dal'

const refDrawersEdit = ref()
const tableData = ref([])

/**
 * 点击添加按钮时的处理函数
 */
const handleClickBtnAdd = () => {
  if (refDrawersEdit.value) {
    refDrawersEdit.value.open({}, { title: '新建汉字结构' })
  }
}

/**
 * 点击编辑按钮时的处理函数
 */
const handleClickBtnEdit = (row: any) => {
  if (refDrawersEdit.value) {
    refDrawersEdit.value.open(row, { title: '编辑汉字结构' })
  }
}

/**
 * 点击删除按钮时的处理函数
 */
const handleClickBtnDelete = async (id: number) => {
  try {
    await Dal.Hanzi.Structure.deleteById(id)
    await initData()
  } catch (error) {
    console.error('删除汉字结构失败', error)
  }
}

/**
 * 编辑抽屉提交后的处理函数
 */
const handleDrawersEditSubmited = async () => {
  await initData()
}

/**
 * 初始化表格数据
 */
const initData = async () => {
  const res = await Dal.Hanzi.Structure.findAll()
  tableData.value = res.data
}

onMounted(async () => {
  await initData()
})
</script>
